package com.dick.base.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dick.base.aop.SmartQuery;
import com.dick.base.mapper.BaseOperateLogMapper;
import com.dick.base.model.BaseOperateLog;
import com.dick.base.session.dto.UserBaseInfo;
import com.dick.base.session.util.SessionUtil;
import com.dick.base.util.DateUtil;
import com.dick.base.util.IdUtil;
import com.dick.base.util.PageInfo;
import com.dick.base.util.SmartQueryUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * 操作日志服务
 */
@Service
public class OperateLogService {

    @Autowired
    private BaseOperateLogMapper baseOperateLogMapper;

    /**
     * 分页查询
     * @param operateLog
     * @param pageInfo
     * @return
     */
    @SmartQuery(clazz = BaseOperateLog.class, likeFields = {"operate", "operateDetail"})
    public Page<BaseOperateLog> operateLogPage(BaseOperateLog operateLog, PageInfo pageInfo) {
        return baseOperateLogMapper.selectPage(SmartQueryUtil.getPage(), SmartQueryUtil.getQueryWrapper());
    }

    /**
     * 新增操作日志
     * @param operate
     * @param operateDetail
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void addLog(String operate, String operateDetail) {
        UserBaseInfo userBaseInfo = SessionUtil.currentUser();
        BaseOperateLog log = new BaseOperateLog();
        log.setOperate(operate);
        if (!StringUtils.isEmpty(operateDetail) && operateDetail.length() > 1024) {
            operateDetail = operateDetail.substring(0, 1024);
        }
        log.setOperateDetail(operateDetail);
        log.setCreateTime(DateUtil.now());
        log.setId(IdUtil.nextId());
        log.setUserName(userBaseInfo.getUsername());
        log.setUserId(userBaseInfo.getId());
        baseOperateLogMapper.insert(log);
    }
}
